package com.tang.juc.VolatileTest;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author tlm
 * @version 1.0
 * @date 2020/4/17 10:03
 * 解决volatile不保证原子性问题
 * 利用juc中的原子包装类型AtomicInteger
 */
public class VolatileDemo3 {
    public static void main(String[] args) {
        MyData3 myData3 = new MyData3();
        for (int i = 1; i <= 20; i++) {
            new Thread(() -> {
                for (int j = 1; j <= 1000; j++) {
                    myData3.addAdd();
                }
            }, String.valueOf(i)).start();
        }
        //等待上面20个线程执行完毕后，用main线程查看计算结果
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName()+"\t number的值为："+myData3.atomicInteger);
    }
}
//资源类
class MyData3{
    //原子包装类型
    AtomicInteger atomicInteger = new AtomicInteger();

    public void addAdd(){
        atomicInteger.getAndIncrement();
    }
}
